import requests
import execjs

def main():
    """
    主函数，处理视频链接并发送API请求
    """
    try:
        # 1. 获取用户输入的视频链接并进行正则匹配
        video_url = input("请输入视频链接：")
        
        if not video_url:
            print("❌ 无效的视频链接")
            return

        # 2. 调用本地JS文件生成动态请求头
        with open('snapany/code.js', 'r', encoding='utf-8') as f:
            js_code = f.read()
        ctx = execjs.compile(js_code)
        footer_data = ctx.call("generateGFooter", video_url)

        # 3. 构建完整的请求头和JSON数据
        headers = {
            'accept': '*/*',
            'accept-language': 'zh',
            'content-type': 'application/json',
            'origin': 'https://snapany.com',
            'priority': 'u=1, i',
            'referer': 'https://snapany.com/',
            'sec-ch-ua': '"Not;A=Brand";v="99", "Microsoft Edge";v="139", "Chromium";v="139"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0',
            'g-footer': footer_data['g-footer'],
            'g-timestamp': footer_data['g-timestamp'],
        }

        json_data = {'link': video_url}

        print("\n正在发送请求...")
        
        # 4. 发送POST请求
        response = requests.post('https://api.snapany.com/v1/extract', headers=headers, json=json_data)
        response.raise_for_status()  # 检查请求是否成功

        # 5. 打印JSON响应
        print("✅ 请求成功！\n")
        # print(json.dumps(response.json(), indent=4, ensure_ascii=False))
        print("标题:", response.json().get('text', '无标题'))
        print("视频链接:", response.json().get('medias')[0].get('resource_url', '无视频链接'))
        print("音频链接:", response.json().get('medias')[-1].get('resource_url', '无音频链接'))
    except FileNotFoundError:
        print("❌ 错误：未找到 'snapany/code.js' 文件。请确保文件路径正确。")
    except requests.exceptions.RequestException as e:
        print(f"❌ 请求失败: {e}")
    except execjs.ProgramError as e:
        print(f"❌ JavaScript执行错误: {e}")

if __name__ == "__main__":
    main()